package com.h3bpm.kumhosunny.crm.controller.createcredentials;

import OThinker.Common.Organization.Models.OrgPost;
import OThinker.Common.Organization.Models.OrgStaff;
import OThinker.Common.Organization.Models.Unit;
import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis.Constants;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceException;
import java.net.URL;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @authormi
 * @date2019/9/24
 */
@Controller
@RequestMapping("/Portal/CRM/createCredentials")
public class CreateCredentialsController extends ControllerBase {

    private static final Logger LOGGER = LoggerFactory.getLogger(ControllerBase.class);
    @Value("${u8_ip}")
    private String u8Ip;
    @Value("${u8_datasource}")
    private String u8Datasource;
    @Value("${u8_database_username}")
    private String u8DatabaseUsername;
    @Value("${u8_database_password}")
    private String u8DatabasePassword;
    @Value("${accid}")
    private String accId;
    @Value("${web_serviceURI}")
    private String webServiceUri;
    @Value("${the_lender_coding}")
    private String theLenderCoding;

    @Override
    public String getFunctionCode() {
        return null;
    }



  @RequestMapping("/credentials")
    @ResponseBody
    public  JSONObject  callSerivce(String instanceId){
      JSONObject result = new JSONObject();
      result.put("data","500");

        try{
            ServiceClient sc = new ServiceClient();
            Options opts = new Options();
            String url = webServiceUri;
            EndpointReference end = new EndpointReference(url);
            opts.setTo(end);
            opts.setAction("http://tempuri.org/InsertAccouch");
            sc.setOptions(opts);
            String xml = getXmlValue(instanceId);
            OMFactory fac = OMAbstractFactory.getOMFactory();
            OMNamespace omNs = fac.createOMNamespace("http://tempuri.org/", "");
            OMElement method = fac.createOMElement("InsertAccouch",omNs);
            OMElement value = fac.createOMElement("strxml",omNs);
            value.setText(xml);
            method.addChild(value);
            OMElement res = sc.sendReceive(method);
            result.put("data",res.getFirstElement().getText());
            LOGGER.info("webservice调用返回结果 "+res.toString());
            LOGGER.info("webservice调用返回结果 "+result.toJSONString());
        }catch(Exception e){
            result.put("data","500");
            e.printStackTrace();
        }
            return result;
    }

     public   String getXmlValue(String instanceId) throws Exception {

            String zdPerson = "";
         OrgPost post = getEngine().getOrganization().GetJobByCode("financialTreasurer");
         if (null != post) {
             List<OrgStaff> orgStaffList = post.getChildList();
           if(orgStaffList!=null && orgStaffList.size()>0){
             User user = (User) getEngine().getOrganization().GetUnit( orgStaffList.get(0).getUserID());
               zdPerson = user.getName();
           }

         }


         SimpleDateFormat simpleDateFormatUpdate=new SimpleDateFormat("yyyy-MM-dd");
         String xml= "<?xml version=\"1.0\" encoding=\"utf-8\"?><voucher>" +
                 "<row>" +
                 "<IP>"+u8Ip+"</IP>" +
                 "<Datasource>"+u8Datasource+"</Datasource>" +
                 "<user>"+u8DatabaseUsername+"</user>" +
                 "<password>"+u8DatabasePassword+"</password>" +
                 "<accid>"+accId+"</accid>" ;

         InstanceData instanceData = new InstanceData(getEngine(),instanceId, User.AdministratorID);
          Unit unit = getEngine().getOrganization().GetUnit(instanceData.getBizObject().getCreatedByParentId());
         User unitUser =  (User)getEngine().getOrganization().GetUnit(instanceData.getBizObject().getCreatedBy());

         Map<String,Object> reimbursement = instanceData.getBizObject().getValueTable();
         BizObject[]  reimbursementDetail= (BizObject[]) reimbursement.get("DetailsCustomers");
         for ( int j =0 ; j<reimbursementDetail.length;j++ ) {

             BizObject obj = reimbursementDetail[j];
             Map<String, Object> zbValueTable = obj.getValueTable();
             String itemObj = zbValueTable.get("entertainmentExpense").toString();
             //报销单号
             String applyReimbursementItem = zbValueTable.get("applyReimbursementItem").toString();
             //客户编码
             String clientNumber = zbValueTable.get("clientNumber").toString();
             String remark = zbValueTable.get("remark").toString();
             JSONArray itemJson=JSONArray.parseArray(itemObj);

             for(int i=0;i<itemJson.size();i++ ){
                 JSONObject itemJs=  itemJson.getJSONObject(i);
                 String subjectCode = itemJs.getString("subject");
                 String subjectValue = itemJs.getString("subjectValue");
               if(j==0 && i==0) {
                   xml += "<initid></initid>" +
                           "<dbill_date>"+simpleDateFormatUpdate.format(new Date())+"</dbill_date>" +
                           "<csign>银付</csign>" +
                           "<ccode>"+subjectCode+"</ccode>" +
                           "<ccode_equal></ccode_equal>" +
                           "<md>"+subjectValue+"</md><mc>0</mc>" +
                           "<cdept_id>"+unit.getDescription().trim()+"</cdept_id>" +
                           "<cperson_id>"+unitUser.getCode()+"</cperson_id>" +
                           "<ccus_id>"+clientNumber+"</ccus_id>" +
                           "<csup_id>ALBB</csup_id>" +
                           "<citem_id></citem_id>" +
                           "<cbill>"+zdPerson+"</cbill>" +
                           "<cdigest>"+remark+"</cdigest>" +
                           "<idoc></idoc>" +
                           "</row>"+"<row>" +
                           "<initid></initid>" +
                           "<dbill_date>"+simpleDateFormatUpdate.format(new Date())+"</dbill_date>" +
                           "<csign>银付</csign>" +
                           "<ccode>100239</ccode>" +
                           "<ccode_equal></ccode_equal>" +
                           "<md></md><mc>"+subjectValue+"</mc>" +
                           "<cdept_id>"+unit.getDescription().trim()+"</cdept_id>" +
                           "<cperson_id>"+unitUser.getCode()+"</cperson_id>" +
                           "<ccus_id>"+clientNumber+"</ccus_id>" +
                           "<csup_id>ALBB</csup_id>" +
                           "<citem_id></citem_id>" +
                           "<cbill>"+zdPerson+"</cbill>" +
                           "<cdigest>"+remark+"</cdigest>" +
                           "<idoc></idoc>" +
                           "</row>";
               }else{

                   xml +=   "<row>" +
                           "<initid></initid>" +
                           "<dbill_date>"+simpleDateFormatUpdate.format(new Date())+"</dbill_date>" +
                           "<csign>银付</csign>" +
                           "<ccode>"+subjectCode+"</ccode>" +
                           "<ccode_equal></ccode_equal>" +
                           "<md>"+subjectValue+"</md><mc>0</mc>" +
                           "<cdept_id>"+unit.getDescription().trim()+"</cdept_id>" +
                           "<cperson_id>"+unitUser.getCode()+"</cperson_id>" +
                           "<ccus_id>"+clientNumber+"</ccus_id>" +
                           "<csup_id>ALBB</csup_id>" +
                           "<citem_id></citem_id>" +
                           "<cbill>"+zdPerson+"</cbill>" +
                           "<cdigest>"+remark+"</cdigest>" +
                           "<idoc></idoc>" +
                           "</row>"+"<row>" +
                           "<initid></initid>" +
                           "<dbill_date>"+simpleDateFormatUpdate.format(new Date())+"</dbill_date>" +
                           "<csign>银付</csign>" +
                           "<ccode>100239</ccode>" +
                           "<ccode_equal></ccode_equal>" +
                           "<md></md><mc>"+subjectValue+"</mc>" +
                           "<cdept_id>"+unit.getDescription().trim()+"</cdept_id>" +
                           "<cperson_id>"+unitUser.getCode()+"</cperson_id>" +
                           "<ccus_id>"+clientNumber+"</ccus_id>" +
                           "<csup_id>ALBB</csup_id>" +
                           "<citem_id></citem_id>" +
                           "<cbill>"+zdPerson+"</cbill>" +
                           "<cdigest>"+remark+"</cdigest>" +
                           "<idoc></idoc>" +
                           "</row>";
               }
             }

         }
         LOGGER.info(zdPerson);
         xml +="</voucher>";

            return xml;
     }




    @RequestMapping("/credenEntertainmentTials")
    @ResponseBody
    public  JSONObject  credenEntertainmentTials(String instanceId){
        JSONObject result = new JSONObject();
        result.put("data","500");

        try{
            ServiceClient sc = new ServiceClient();
            Options opts = new Options();
            String url = webServiceUri;
            EndpointReference end = new EndpointReference(url);
            opts.setTo(end);
            opts.setAction("http://tempuri.org/InsertAccouch");
            sc.setOptions(opts);
            String xml = callCredenEntertainmentTials(instanceId);
            OMFactory fac = OMAbstractFactory.getOMFactory();
            OMNamespace omNs = fac.createOMNamespace("http://tempuri.org/", "");
            OMElement method = fac.createOMElement("InsertAccouch",omNs);
            OMElement value = fac.createOMElement("strxml",omNs);
            value.setText(xml);
            method.addChild(value);
            OMElement res = sc.sendReceive(method);
            result.put("data",res.getFirstElement().getText());
            LOGGER.info("webservice调用返回结果 "+result.toJSONString());

        }catch(Exception e){
            result.put("data","500");
            e.printStackTrace();
        }
        return result;
    }

    public   String callCredenEntertainmentTials(String instanceId) throws Exception {


        String zdPerson = "";
        OrgPost post = getEngine().getOrganization().GetJobByCode("financialTreasurer");
        if (null != post) {
            List<OrgStaff> orgStaffList = post.getChildList();
            if(orgStaffList!=null && orgStaffList.size()>0){
                User user = (User) getEngine().getOrganization().GetUnit( orgStaffList.get(0).getUserID());
                zdPerson = user.getName();
            }

        }


        SimpleDateFormat simpleDateFormatUpdate=new SimpleDateFormat("yyyy-MM-dd");
        String xml= "<?xml version=\"1.0\" encoding=\"utf-8\"?><voucher>" +
                "<row>" +
                "<IP>"+u8Ip+"</IP>" +
                "<Datasource>"+u8Datasource+"</Datasource>" +
                "<user>"+u8DatabaseUsername+"</user>" +
                "<password>"+u8DatabasePassword+"</password>" +
                "<accid>"+accId+"</accid>" ;

        InstanceData instanceData = new InstanceData(getEngine(),instanceId, User.AdministratorID);
        Unit unit = getEngine().getOrganization().GetUnit(instanceData.getBizObject().getCreatedByParentId());
        User unitUser =  (User)getEngine().getOrganization().GetUnit(instanceData.getBizObject().getCreatedBy());

        Map<String,Object> reimbursement = instanceData.getBizObject().getValueTable();
        BizObject[]  reimbursementDetail= (BizObject[]) reimbursement.get("entertainmentExpenseMsg");
        for ( int j =0 ; j<reimbursementDetail.length;j++ ){

            BizObject obj = reimbursementDetail[j];
            Map<String, Object> zbValueTable = obj.getValueTable();
            //报销单号
            String applyReimbursementItem = zbValueTable.get("processNumber").toString();
            //客户编码
            String clientNumber = zbValueTable.get("customerNumber").toString();
            String remark ="";
                String subjectCode =zbValueTable.get("cost").toString();
                String subjectValue = zbValueTable.get("entertainmentExpense").toString();
                if(j==0) {
                    xml += "<initid></initid>" +
                            "<dbill_date>"+simpleDateFormatUpdate.format(new Date())+"</dbill_date>" +
                            "<csign>银付</csign>" +
                            "<ccode>"+subjectCode+"</ccode>" +
                            "<ccode_equal></ccode_equal>" +
                            "<md>"+subjectValue+"</md><mc>0</mc>" +
                            "<cdept_id>"+unit.getDescription().trim()+"</cdept_id>" +
                            "<cperson_id>"+unitUser.getCode()+"</cperson_id>" +
                            "<ccus_id>"+clientNumber+"</ccus_id>" +
                            "<csup_id>ALBB</csup_id>" +
                            "<citem_id></citem_id>" +
                            "<cbill>"+unitUser.getName()+"</cbill>" +
                            "<cdigest>"+remark+"</cdigest>" +
                            "<idoc></idoc>" +
                            "</row>"+"<row>" +
                            "<initid></initid>" +
                            "<dbill_date>"+simpleDateFormatUpdate.format(new Date())+"</dbill_date>" +
                            "<csign>银付</csign>" +
                            "<ccode>100239</ccode>" +
                            "<ccode_equal></ccode_equal>" +
                            "<md></md><mc>"+subjectValue+"</mc>" +
                            "<cdept_id>"+unit.getDescription().trim()+"</cdept_id>" +
                            "<cperson_id>"+unitUser.getCode()+"</cperson_id>" +
                            "<ccus_id>"+clientNumber+"</ccus_id>" +
                            "<csup_id>ALBB</csup_id>" +
                            "<citem_id></citem_id>" +
                            "<cbill>"+zdPerson+"</cbill>" +
                            "<cdigest>"+remark+"</cdigest>" +
                            "<idoc></idoc>" +
                            "</row>";
                }else{
                    xml +=   "<row>" +
                            "<initid></initid>" +
                            "<dbill_date>"+simpleDateFormatUpdate.format(new Date())+"</dbill_date>" +
                            "<csign>银付</csign>" +
                            "<ccode>"+subjectCode+"</ccode>" +
                            "<ccode_equal></ccode_equal>" +
                            "<md>"+subjectValue+"</md><mc>0</mc>" +
                            "<cdept_id>"+unit.getDescription().trim()+"</cdept_id>" +
                            "<cperson_id>"+unitUser.getCode()+"</cperson_id>" +
                            "<ccus_id>"+clientNumber+"</ccus_id>" +
                            "<csup_id>ALBB</csup_id>" +
                            "<citem_id></citem_id>" +
                            "<cbill>"+zdPerson+"</cbill>" +
                            "<cdigest>"+remark+"</cdigest>" +
                            "<idoc></idoc>" +
                            "</row>"+"<row>" +
                            "<initid></initid>" +
                            "<dbill_date>"+simpleDateFormatUpdate.format(new Date())+"</dbill_date>" +
                            "<csign>银付</csign>" +
                            "<ccode>100239</ccode>" +
                            "<ccode_equal></ccode_equal>" +
                            "<md></md><mc>"+subjectValue+"</mc>" +
                            "<cdept_id>"+unit.getDescription().trim()+"</cdept_id>" +
                            "<cperson_id>"+unitUser.getCode()+"</cperson_id>" +
                            "<ccus_id>"+clientNumber+"</ccus_id>" +
                            "<csup_id>ALBB</csup_id>" +
                            "<citem_id></citem_id>" +
                            "<cbill>"+zdPerson+"</cbill>" +
                            "<cdigest>"+remark+"</cdigest>" +
                            "<idoc></idoc>" +
                            "</row>";
                }
            }
        xml +="</voucher>";
        LOGGER.info(zdPerson);
        return xml;
    }




}
